// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package clientGUI;

import librarianPanels.BorrowBookPanel;
import librarianPanels.InventoryManagementPanel;
import librarianPanels.MessagesPanel;
import librarianPanels.SearchABookPanel;
import librarianPanels.ViewBookOrdersFrame;
import librarianPanels.WatchReaderCardPanel;
import libraryManagerPanels.ReportsPanel;
import libraryManagerPanels.WatchEmployee;
import libraryManagerPanels.freezeSubscriptionPanel;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import ocsf.client.AbstractClient;
import pdf.PDFDocument;
import pdf.PDFfile;
import subscriberPanels.ExtendBorrowPanel;
import subscriberPanels.UpdateDetailsPanel;
import subscriberPanels.ViewMyReaderCardPanel;

/**
 * This class overrides some of the methods defined in the abstract
 * superclass in order to give more functionality to the client.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;
 * @author Fran&ccedil;ois B&eacute;langer
 * @version July 2000
 */
public class ChatClient extends AbstractClient 
{
	public String ClientID ; 
  //Instance variables **********************************************
  
  /**
   * The interface type variable.  It allows the implementation of 
   * the display method in the client.
   */
/*  ChatIF clientUI; */

  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the chat client.
   *
   * @param host The server to connect to.
   * @param port The port number to connect on.
   * @param clientUI The interface type variable.
   */
  

	
	public ChatClient(String host, int port)  throws IOException 
	{	
		super(host,port);
		 openConnection();
	}

  
  //Instance methods ************************************************
    
  /**
   * This method handles all data that comes in from the server.
   *
   * @param msg The message from the server.
   */
  @SuppressWarnings("unchecked")
public void handleMessageFromServer(Object msg) 
  {
	ArrayList<Object> y=(ArrayList<Object>)msg;
    String x=(String)y.get(0);
    if(x.contains("Search"))
    {
    	SearchABookPanel.changeTableContent((String[][])y.get(1));
    }
    else if(x.contentEquals("LibrarianMessages"))
    {
    	MessagesPanel.changeTableContent((String[][])y.get(1));
    }
    else if(x.contentEquals("DeleteMessage"))
    {
    	JOptionPane.showMessageDialog(new JFrame(),	"Deleted Successfully!");
    	MessagesPanel.changeTableContent((String[][])y.get(1));
    }
    else if(x.contentEquals("deleteTest"))
    {
		String temp[]={"quit"};
		MainGUI.OBLClient.handleMessageFromClient(temp);
    }
    else if(x.contentEquals("ServerStopped"))
    {
    	JOptionPane.showMessageDialog(new JFrame(),	"Server Stopped - disconnecting!","Error",JOptionPane.ERROR_MESSAGE);
    	System.exit(1);
    }
    else if(x.contentEquals("cancelOrder"))
    {
		ViewBookOrdersFrame.changeTableContent((String[][])y.get(1));
    	JOptionPane.showMessageDialog(new JFrame(),	"Order Canceled!");
    }
    else if(x.contentEquals("EmployeeAndSubscriber"))
    {
    	WatchEmployee.changeTableContentEmployees((String[][])y.get(1));
    	WatchEmployee.changeTableContentSubscribers((String[][])y.get(2));
    }
    else if(x.contains("Login"))
    {
    	String rst=(String)y.get(1);
    	if(rst.contentEquals("FAIL"))
    	{
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"Login Failed - Wrong username/password! ","Error",JOptionPane.ERROR_MESSAGE);
    	}
    	else if(rst.contentEquals("Success"))
    	{
    		String[][] temp=(String[][])y.get(2);
    		ConnectionGUI.user=new User(temp[0]);
    		MainGUI.buttonsPanelChange(temp[0][5],temp[0][1],temp[0][2]);
    	}
    	else if(rst.contentEquals("already"))
    	{
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"Login Failed - you are already logged in!","Error",JOptionPane.ERROR_MESSAGE);
    	}
    	else if(rst.contains("locked"))
    	{
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"Login Failed - account locked!","Error",JOptionPane.ERROR_MESSAGE);
    	}
    }
    else if(x.contentEquals("logoff"))
    {
		MainGUI.buttonsPanelChange("0","dummy","dummy");
		MainGUI.middlePanelChange((new LoginPanel()));
		ConnectionGUI.user=null;
    }
    else if(x.contains("borrow"))
    {
    	if(!MainGUI.testmode)
    		BorrowBookPanel.ShowMsgFromServer((String)y.get(1));
    }
    
    else if(x.contains("newReaderCard"))
    {
    	if(!MainGUI.testmode)
    		JOptionPane.showMessageDialog(null , (String)y.get(1));
    }
    else if(x.contains("watchRedearCard"))
    {
    	if(!(x.contains("No Such Subscriber!!")))
    	{
    		WatchReaderCardPanel.changeTableContent((String[][])y.get(3),(String[][])y.get(2),(String[][])y.get(1),true);
    		freezeSubscriptionPanel.changeButton(((String[][])y.get(1))[0][4]);
    	}
    	else
    	{
    		WatchReaderCardPanel.changeTableContent(null,null,null,false);
    		freezeSubscriptionPanel.changeButton("0");
    	}
    	
    }
    else if(x.contains("BorrowedBooks"))
    	ExtendBorrowPanel.changeTableContent((String[][])y.get(1));

    else if(x.contains("ExtendBooks"))
    		ExtendBorrowPanel.changeTableContent((String[][])y.get(1));    	
    
    else if(x.contains("NotExtend"))
    {
    	if(!MainGUI.testmode)
    	JOptionPane.showMessageDialog(null , (String)y.get(1));
    }
    
    else if(x.contains("Reports"))
    {
    	if(y.get(1).toString().contentEquals("Activity"))
    		ReportsPanel.updateFieldsActivity((String[])y.get(2));
    	else if(y.get(1).toString().contentEquals("Borrowed"))
    	{
    		ReportsPanel.updateFieldsBorrowed((String[])y.get(2));
    		ReportsPanel.setDataForHisto((Double[])y.get(3),(Double[])y.get(4));
    	}
    	else 
    	{
	    	ReportsPanel.updateFieldsLates((String[])y.get(1));
    		ReportsPanel.setDataForHisto((HashMap<String,Double>)y.get(2),(HashMap<String,Double>)y.get(3),(String[])y.get(4));
    	}
    }   
    else if(x.contains("WatchIndex"))
    {
    	try {
    		if(y.get(1).toString().contentEquals("unknown"))
    		{
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR , Index unavilable!");
    		}
    		else
    		{
	    		File test=new File("temp.pdf");
	    		PDFfile temp=(PDFfile)y.get(1);
				Files.write(test.toPath(), temp.input,StandardOpenOption.CREATE);
				PDFDocument temp2=new PDFDocument("temp.pdf");
				temp2.begin();
    		}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    else if(x.contains("OrderBook"))
    {
    	switch ((String)y.get(1))
    	{
    	case "true":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"Book Ordered!");
    		break;
    	case "full":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Queue is full!","Error",JOptionPane.ERROR_MESSAGE);
    		break;
    	case "exists":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR - You already ordered this book!","Error",JOptionPane.ERROR_MESSAGE);
    		break;
    	case "frozen":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Your reader card is frozen!","Error",JOptionPane.ERROR_MESSAGE);
    		break;
    	case "borrowed":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR - You already have this book!","Error",JOptionPane.ERROR_MESSAGE);
    		break;
    	case "orderlist":
    		if(!MainGUI.testmode)
    			JOptionPane.showMessageDialog(new JFrame(),	"ERROR - You already ordered this book and it arrived!","Error",JOptionPane.ERROR_MESSAGE);
    		break;
    	}
    	MainGUI.ordered=(String)y.get(1);
    }
    else if(x.contains("ViewMyReaderCard"))
    {
    	ViewMyReaderCardPanel.changeTableContentMyHistory((String[][])y.get(1));
    	ViewMyReaderCardPanel.changeTableContentMyBook((String[][])y.get(2));
    	ViewMyReaderCardPanel.changeDetailsContent((String[][])y.get(3));
    	ViewMyReaderCardPanel.changeTableContentMyActions((String[][])y.get(4));
    }
    
    else if(x.contains("BringDetails"))
    {
    	UpdateDetailsPanel.changeTextFieldContent((String[][])y.get(1));
    }
    else if(x.contains("UpdateDetails"))
    {
    	if(!MainGUI.testmode)
    		UpdateDetailsPanel.ShowMsgFromServer((String)y.get(1));    	
    }
    else if(x.contains("freeze"))
    {
    	freezeSubscriptionPanel.changeButton((String)y.get(1));
    	if(!MainGUI.testmode)
    		freezeSubscriptionPanel.ShowMsgFromServer((String)y.get(2));
    	
    }
    else if(x.contains("Return"))
    {
    	if(!MainGUI.testmode)
    		BorrowBookPanel.ShowMsgFromServer((String)y.get(1));    	
    }
    else if(x.contains("UpdateReturnDate"))
    {
    	WatchReaderCardPanel.ShowMsgFromServer((String)y.get(1));
    }
    else if(x.contains("InventoryS"))
    {
    	InventoryManagementPanel.changeTableContent((String[][])y.get(1));
    }
    else if(x.contains("Remove"))
    {
    	BorrowBookPanel.ShowMsgFromServer((String)y.get(1));
    }
    else if(x.contains("AddCopy"))
    {
    	BorrowBookPanel.ShowMsgFromServer((String)y.get(1));
    }
    else if(x.contains("newTitle"))
    {
    	BorrowBookPanel.ShowMsgFromServer((String)y.get(1));
    }
    else if(x.contains("ViewBookOrders"))
    {
    	String [][]temp =(String[][])y.get(1);
    	if(!MainGUI.testmode)
    	{
	    	if(temp.length!=0)
	    	{
	    		ViewBookOrdersFrame z =new ViewBookOrdersFrame(SearchABookPanel.table.getModel().getValueAt(SearchABookPanel.table.getSelectedRow(),1).toString(),(String)y.get(2));
	    		ViewBookOrdersFrame.changeTableContent((String[][])y.get(1));
				z.pack();
				z.setVisible(true);
	    	}
	    	else
	    	{
	    			JOptionPane.showMessageDialog(new JFrame(),	"Book doesn't have orders!","Error",JOptionPane.ERROR_MESSAGE);
	    	}
    	}
    }
    MainGUI.done=true;
  }
  /**
   * This method handles all data coming from the UI            
   *
   * @param message The message from the UI.    
   */
  public void handleMessageFromClient(String[] message)
  {
    try
    {
    	MainGUI.done=false;
    	sendToServer(message);
    }
    catch(IOException e)
    {
		JOptionPane.showMessageDialog(new JFrame(),"Could not send message to server.  Terminating client.");
      quit();
    }
  }
  /**
   * This method terminates the client.
   */
  public void quit()
  {
    try
    {
      closeConnection();
    }
    catch(IOException e) {}
    System.exit(0);
  }
}
//End of ChatClient class
